#include "atadrive.h"
#include "integer.h"
#include <string.h>
#include <stdlib.h>
#include <stdio.h>

static char *RawDiskFile = "sdb_1Gfat.img";
static FILE *pFpDisk = NULL;

int ATA_disk_status(void)
{
	DEBUG("ATA_disk_status() always return 0\n");
	return 0;
}

int ATA_disk_initialize(void)
{
	/* 
	 * I think FatFS opens once only, but the below three lines
	 * make code more stable. They may be removed only if they are
	 * proven to be useless.
	 */
	if (pFpDisk != NULL) {
		DEBUG("%s has been opend.\n", RawDiskFile);
		return 0;
	}
		
	pFpDisk = fopen(RawDiskFile, "rb+");

	if (pFpDisk == NULL) {
		DEBUG("Cannot open %s\n", RawDiskFile);
		return -2;
	} else {
		DEBUG("ATA_disk_initialize() OK\n");
		return 0;
	}
}

int ATA_disk_read(
				BYTE *buff,		/* Data buffer to store read data */
				DWORD sector,	/* Sector address in LBA */
				UINT count		/* Number of sectors to read */
				)
{
	int bytes_read = 0;

	DEBUG("Sector: %d Sector Count: %d\n", sector, count);

	fseek(pFpDisk, sector * 512, SEEK_SET);
	bytes_read = fread(buff, 1, count * 512, pFpDisk);

	return 0;
}

int ATA_disk_write(
				const BYTE *buff,		/* Data buffer to store read data */
				DWORD sector,	/* Sector address in LBA */
				UINT count		/* Number of sectors to read */
				)
{
	int bytes_write = 0;

	fseek(pFpDisk, sector * 512, SEEK_SET);
	bytes_write = fwrite(buff, 1, count * 512, pFpDisk);

	return 0;
}

int ATA_disk_ioctl(
				BYTE cmd,		/* Control code */
				void *buff		/* Buffer to send/receive control data */
				)
{
	DEBUG("ATA_disk_ioctl() always return OK\n");
	return 0;
}

#include <time.h>
/* we can use RTC to get time */
struct fattime{
#ifdef _BIG_ENDIAN_
	unsigned year:7;
	unsigned mon:4;
	unsigned mday:5;
	unsigned hour:5;
	unsigned min:6;
	unsigned sec:5;
#else
	unsigned sec:5;
	unsigned min:6;
	unsigned hour:5;
	unsigned mday:5;
	unsigned mon:4;
	unsigned year:7;
#endif
};

DWORD get_fattime (void)
{
	DWORD ret;
	struct tm *ptm;
	struct fattime ft;
	time_t t;

	t = time(NULL);
	ptm = gmtime(&t);

	ft.year = ptm->tm_year + 1900 - 1980;
	ft.mon = ptm->tm_mon + 1;
	ft.mday = ptm->tm_mday;
	ft.hour = ptm->tm_hour;
	ft.min = ptm->tm_min;
	ft.sec = ptm->tm_sec;

	ret = *(DWORD*)(&ft);
	return ret;
}
